from html.parser import HTMLParser
from urllib.request import urlretrieve
import sys
import re
import pokeparser

class iteminfo(HTMLParser):
	def __init__(self, name, url):
		super().__init__()
		self.in_table = self.in_tr = self.in_info = self.in_fling = self.in_h2 = self.in_effect = False
		self.p = pokeparser.pokeparser()
		self.text = self.p.gettext(url)
		self.name = name
		self.info = self.fling = self.effect = ''

	def handle_starttag(self, tag, attrs):
		attrs = dict(attrs)
		title = attrs.get('title','')
		classs = attrs.get('class','')
		if tag == 'tbody':
			self.in_table = True
		elif self.in_table:
			if tag == 'a' and re.search('投掷（招式）', title):
				self.in_fling = True
			elif tag == 'tr' and classs != 'hide':
				self.in_tr = True
			elif classs == 'hide':
				self.in_tr = False
			elif self.in_tr and tag == 'td' and self.in_info:
				self.info += '/'
		elif tag == 'h2':
			self.in_h2 = True
			if self.in_effect:
				self.in_effect = False

	def handle_data(self, data):
		data = str(data).strip('\n')
		# 获得道具详细描述：
		if data != '' and self.in_tr and self.fling == '':
			if re.search('这个道具.*?', data):
				self.in_info = True
			elif re.search('首次出现', data):
				self.in_info = False
			if self.in_info:
				self.info += data
		# 获得道具投掷伤害：
		if self.in_fling:
			if re.search('^[0-9]+$', data):
				self.fling = data
				self.in_fling = False
			elif re.search('无法投掷', data):
				self.fling = '-1'
				self.in_fling = False
		# 获得道具效果：
		elif re.search('.*?效果',data) and self.in_h2:
			self.in_effect = True
		elif data != '' and self.in_effect:
			self.effect += data

	def handle_endtag(self, tag):
		if tag == 'tbody':
			self.in_table = False
		elif tag == 'tr':
			self.in_tr = False
		elif tag == 'h2':
			self.in_h2 = False

def test():
	i = iteminfo('讲究围巾', r'https://wiki.52poke.com/zh-hans/%E8%AE%B2%E7%A9%B6%E5%9B%B4%E5%B7%BE%EF%BC%88%E9%81%93%E5%85%B7%EF%BC%89')
	i.feed(i.text)
	print(i.name,i.info,i.fling,i.effect)
	i.close()

if __name__ == "__main__":
	test()